package com.code.algorithm;

/**
 * 判断链表是否有环
 */

public class HasCycle {

    class ListNode{
        int val;
        ListNode next;
        public ListNode(int val, ListNode next){
            this.val = val;
            this.next = next;
        }
    }



    public boolean hasCycle(ListNode head){
        if(head == null || head.next == null){
            return false;
        }
        //定义一个快指针
        ListNode quick = head;
        //定义一个慢指针
        ListNode slow = head;
        if(quick.next.next == null){
            if(slow.next == slow){
                return true;
            }else{
                return false;
            }
        }
        while(slow != null){
            if(quick.next ==null || quick.next.next == null){
                return false;
            }
            quick = quick.next.next;
            slow = slow.next;

            if(quick == slow){
                return true;
            }
        }

        return false;
    }
}
